<!-- views/login/LoginForm.vue -->
<template>
  <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      label-position="top"
      @submit.prevent="handleLogin"
  >
    <el-form-item label="用户名" prop="username">
      <el-input
          v-model="loginForm.username"
          placeholder="请输入用户名"
          size="large"
          prefix-icon="el-icon-user"
      />
    </el-form-item>

    <el-form-item label="密码" prop="password">
      <el-input
          v-model="loginForm.password"
          placeholder="请输入密码"
          type="password"
          size="large"
          prefix-icon="el-icon-lock"
          show-password
      />
    </el-form-item>

    <el-form-item>
      <el-button
          type="primary"
          size="large"
          native-type="submit"
          class="login-btn"
          :loading="loading"
      >
        登录系统
      </el-button>
    </el-form-item>

    <div class="login-footer">
      <el-link type="primary" :underline="false">忘记密码?</el-link>
      <el-divider direction="vertical" />
      <el-link type="primary" :underline="false">注册账号</el-link>
    </div>
  </el-form>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { login } from '@/api/auth';
import { useUserStore } from '@/store/modules/user';

// 用户信息数据
const userData = {
  student: {
    username: 'student_1001',
    password: 'password123'
  },
  teacher: {
    username: 'teacher_zhang',
    password: 'password123'
  },
  admin: {
    username: 'admin01',
    password: '123456'
  }
};

const props = defineProps({
  userType: {
    type: String as () => 'student' | 'teacher' | 'admin',
    required: true
  }
});

const router = useRouter();
const userStore = useUserStore();
const loginForm = ref({
  username: userData[props.userType].username,
  password: userData[props.userType].password
});
const loading = ref(false);
const defaultAvatar = 'https://example.com/default-avatar.png';

// 监听userType变化，更新表单默认值
watch(() => props.userType, (newVal) => {
  loginForm.value = {
    username: userData[newVal].username,
    password: userData[newVal].password
  };
});

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度在4到20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ]
};
const handleLogin = async () => {
  try {
    loading.value = true;
    let result = await login(loginForm.value);

    if (result.success && result.data?.success) {
      // 从data字段中获取实际数据
      const responseData = result.data;

      // 字段映射：确保type字段正确设置
      const userData = {
        ...responseData.user,
        type: responseData.user?.role?.toLowerCase() as UserType || 'student'
      };

      userStore.setToken(responseData.token!);
      userStore.setUserInfo(userData);

      // 保存到本地存储（关键修改）
      localStorage.setItem('userInfo', JSON.stringify(responseData.user));
      localStorage.setItem('token', responseData.token);

      // 如果是老师，保存teacherId到本地存储（用于API调用）
      if (userData.type === 'teacher') {
        localStorage.setItem('teacherId', responseData.user.teacherId || responseData.user.id || responseData.teacherId);
      }

      // 保存权限信息到本地存储（新增）
      if (responseData.permissions) {
        localStorage.setItem('permissions', JSON.stringify(responseData.permissions));
      }

      // 保存角色信息到本地存储（新增）
      if (responseData.roles) {
        localStorage.setItem('roles', JSON.stringify(responseData.roles));
      }

      ElMessage.success(responseData.message || '登录成功');

      // 立即跳转，不需要延迟
      setTimeout(() => {
        router.push(`/${userData.type}/dashboard`);
      }, 500);
    } else {
      ElMessage.error(result.data?.message || result.message || '登录失败');
    }
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '登录异常');
  } finally {
    loading.value = false;
  }
};

const emit = defineEmits(['login-success']);
</script>

<style scoped>
.login-btn {
  width: 100%;
  margin-top: 10px;
}

.login-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  color: #999;
}

.el-divider {
  margin: 0 15px;
}
</style>
